package com.cskaoyan.controller.wxcontroller;

import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.vo.GoodsDetailVo;
import com.cskaoyan.bean.vo.wx.GrouponVo;
import com.cskaoyan.bean.vo.wx.mygroupon.AddressDetailVO;
import com.cskaoyan.beanwx.bo.OrderBaseBo;
import com.cskaoyan.beanwx.bo.OrderCommentBo;
import com.cskaoyan.beanwx.vo.OrderDetailVo;
import com.cskaoyan.beanwx.vo.OrderGoodsVo;
import com.cskaoyan.beanwx.vo.OrderListVo;
import com.cskaoyan.exception.DataDisplayException;
import com.cskaoyan.service.*;
import com.cskaoyan.utils.DateTransforUtil;
import com.cskaoyan.utils.IntegraleUtil;
import com.cskaoyan.utils.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: lds
 * @clsss: OrderController
 */
@RestController
@RequestMapping("wx/order")
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    AddressService addressService;

    @Autowired
    CartService cartService;

    @Autowired
    UserService userService;

    @Autowired
    PromotionService promotionService;

    @Autowired
    GoodsService goodsService;

    /**
     * @author: lds
     * @title: orderPrepay
     * @description:
     * @param: [orderId]
     * @return: com.cskaoyan.bean.vo.BaseRespVo
     */
    @RequestMapping("prepay")
    public BaseRespVo orderPrepay(@RequestBody Map<String, String> orderId) throws DataDisplayException {

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer orderId1 = Integer.parseInt(orderId.get("orderId"));
        Order order = orderService.queryOrderById(orderId1);
        if (order.getGrouponPrice() != null && (order.getGrouponPrice().compareTo(new BigDecimal(0.00)) != 0)) {
            return BaseRespVo.fail();
        }
//        Integer integer = orderService.changePrepayOrder(user, orderId1);
//        if (integer != 1) {
//            throw new DataDisplayException();
//        }
        return BaseRespVo.ok();
    }

    /**
     * @author: 刘东升
     * @title: orderComment
     * @description:
     * @param: [orderCommentBo]
     * @return: com.cskaoyan.bean.vo.BaseRespVo
     */
    @RequestMapping("comment")
    public BaseRespVo orderComment(@RequestBody OrderCommentBo orderCommentBo) throws DataDisplayException {


        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer integer = orderService.addComment(orderCommentBo, user);
        if (integer != 1) {
            throw new DataDisplayException();
        }
        return BaseRespVo.ok();
    }

    @RequestMapping("list")
    public BaseRespVo orderList(OrderBaseBo orderBaseBo) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        OrderListVo orderListVo = orderService.queryUserOrderDetail(orderBaseBo, user);

        return BaseRespVo.ok(orderListVo);
    }

    @RequestMapping("detail")
    public BaseRespVo orderDetail(Integer orderId) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        OrderDetailVo orderDetailVo = orderService.queryOrderByOrderId(user, orderId);
        return BaseRespVo.ok(orderDetailVo);
    }

    @RequestMapping("cancel")
    public BaseRespVo orderCancel(@RequestBody Map orderId) throws DataDisplayException {

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        Integer orderId1 = (Integer) orderId.get("orderId");
        Integer integer = orderService.changeCancelOrder(user, orderId1);
        if (integer != 1) {
            throw new DataDisplayException();
        }
        return BaseRespVo.ok();
    }

    @RequestMapping("confirm")
    public BaseRespVo orderConfirm(@RequestBody Map orderId) throws DataDisplayException {

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer orderId1 = (Integer) orderId.get("orderId");
        Integer integer = orderService.changeConfirmOrder(user, orderId1);
        if (integer != 1) {
            throw new DataDisplayException();
        }
        return BaseRespVo.ok();
    }


    @RequestMapping("refund")
    public BaseRespVo orderRefund(@RequestBody Map orderId) throws DataDisplayException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer orderId1 = (Integer) orderId.get("orderId");
        Integer integer = orderService.changeRefundOrder(user, orderId1);
        if (integer != 1) {
            throw new DataDisplayException();
        }
        return BaseRespVo.ok();
    }

    @RequestMapping("delete")
    public BaseRespVo orderDelete(@RequestBody Map orderId) throws DataDisplayException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer orderId1 = (Integer) orderId.get("orderId");
        Integer integer = orderService.changeDeleteOrder(user, orderId1);
        if (integer != 1) {
            throw new DataDisplayException();
        }

        return BaseRespVo.ok();
    }

    @RequestMapping("submit")
    public BaseRespVo orderSubmit(@RequestBody Map<String, String> orderId) throws DataDisplayException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if (user == null) {
            return BaseRespVo.fail("请登录");
        }
        Integer orderId1 = null;
        try {
            Integer integer = orderService.changeDeleteOrder(user, orderId1);
            if (integer != 1) {
                throw new DataDisplayException();
            }

            return BaseRespVo.ok();
        } catch (Exception e) {
            int addressId = Integer.parseInt(orderId.get("addressId"));
            int cartId = Integer.parseInt(orderId.get("cartId"));
            int couponId = Integer.parseInt(orderId.get("couponId"));
            int grouponLinkId = Integer.parseInt(orderId.get("grouponLinkId"));
            int grouponRulesId = Integer.parseInt(orderId.get("grouponRulesId"));
            String grouponPriceStr = orderId.get("grouponPrice");
            BigDecimal grouponPrice = new BigDecimal(0);
            if (grouponPriceStr != null) {
                grouponPrice = new BigDecimal(grouponPriceStr);
            }

            AddressDetailVO addressDetailVO = addressService.addressDetail(addressId);
            List<Cart> cartList = cartService.queryCartById(cartId);
            Coupon coupon = promotionService.queryCouponById(couponId);

            String message = orderId.get("message");
            Order order = new Order();
            Date date = new Date();


            order.setAddress(addressDetailVO.getAddress());
            order.setAddTime(date);
            // 初始评论为空
            order.setComments(null);
            // 无确认时间
            order.setConfirmTime(null);
            order.setConsignee(addressDetailVO.getName());
            // 优惠券减免价钱
            if (coupon != null) {
                order.setCouponPrice(coupon.getDiscount());
            } else {
                order.setCouponPrice(new BigDecimal(0));
            }
            order.setDeleted(false);
            // 一小时后关闭
            order.setEndTime(new Date(date.getTime() + 60 * 60 * 1000));
            // 配送费用 默认不要钱 todo
            order.setFreightPrice(new BigDecimal(0));
            // 商品总价钱=购物车价钱
            BigDecimal cartPrice = new BigDecimal(0);
            for (Cart cart : cartList) {
                cartPrice = cartPrice.add(cart.getPrice());
            }
            order.setGoodsPrice(cartPrice);
            order.setGrouponPrice(grouponPrice);
            // 自增
            order.setId(null);

            // 积分减免，规则：商品总价的10%可以使用积分抵扣，1积分=1元
            int integrale = user.getIntegral();
            BigDecimal integralePrice = IntegraleUtil.getIntegralePrice(cartPrice, integrale);
            order.setIntegralPrice(integralePrice);

            order.setMessage(message);
            order.setMobile(addressDetailVO.getMobile());
            // 订单费用， = goods_price + freight_price - coupon_price'
            BigDecimal goodsPrice = order.getGoodsPrice();
            BigDecimal freightPrice = order.getFreightPrice();
            BigDecimal couponPrice = order.getCouponPrice();
            if (couponPrice != null) {
                order.setOrderPrice(goodsPrice.add(freightPrice).subtract(couponPrice));
            } else {
                order.setOrderPrice(goodsPrice.add(freightPrice));
            }
//            order.setOrderPrice(order.getGoodsPrice().add(order.getFreightPrice()).subtract(order.getCouponPrice()));
            // '实付费用， = order_price - integral_price',
            order.setActualPrice(order.getOrderPrice().subtract(order.getIntegralPrice()));
            // 根据当前时间生成orderSn
            String orderSn = DateTransforUtil.dateTransToString(date);
            order.setOrderSn(orderSn);
            // 首次添加时间就是第一次更新时间
            order.setUpdateTime(date);
            order.setUserId(user.getId());


            // 如果是团购，groupon要添加数据
            if (!"0".equals(grouponPriceStr)) {
                // 状态初始为未付款 101
                order.setOrderStatus((short) 101);
                // 支付id
                order.setPayId(null);
                order.setPayTime(null);
                // 默认都是顺丰发货
                order.setShipChannel(null);
                // 编号
                order.setShipSn(null);
                // 假设 7天后发货
                order.setShipTime(null);
                orderService.addOrder(order);

                // 使用优惠券，couponUser要减少
                CouponUser couponUser = new CouponUser();
                couponUser.setStatus((short) 1);
                couponUser.setUsedTime(date);
                couponUser.setUpdateTime(date);
                couponUser.setOrderId(order.getId());
                promotionService.changeCouponUserByCouponIdAndUserId(couponUser, couponId, user.getId());

                // 添加order后添加orderGoods
                for (Cart cart : cartList) {
                    // orderGoods增加
                    Integer goodsId = cart.getGoodsId();
                    GoodsDetailVo goodsDetailVo = goodsService.queryGoodsDetail(goodsId);
                    OrderGoods orderGoods = new OrderGoods();

                    orderGoods.setAddTime(date);
                    orderGoods.setComment(null);
                    orderGoods.setDeleted(false);
                    orderGoods.setGoodsId(cart.getGoodsId());
                    orderGoods.setGoodsName(cart.getGoodsName());
                    orderGoods.setGoodsSn(cart.getGoodsSn());
                    // 自增
                    orderGoods.setId(null);
                    orderGoods.setNumber(cart.getNumber());
                    orderGoods.setOrderId(order.getId());
                    orderGoods.setPicUrl(goodsDetailVo.getGoods().getPicUrl());
                    // todo 不知道什么价格 写了一个零售价格
                    orderGoods.setPrice(goodsDetailVo.getGoods().getRetailPrice());
                    orderGoods.setProductId(cart.getProductId());
                    orderGoods.setSpecifications(cart.getSpecifications());
                    orderGoods.setUpdateTime(date);
                    orderService.addOrderGoods(orderGoods);
                }


                Groupon groupon = new Groupon();
                groupon.setAddTime(date);

                // 如果grouponLinkId是0 就是发起者
                if (grouponLinkId == 0) {
                    groupon.setCreatorUserId(user.getId());
                } else {
                    // grouponLinkeId是发起者用户id
                    groupon.setCreatorUserId(grouponLinkId);
                }
                groupon.setDeleted(false);
                // 创建者新生成一条grouponId
                List<Groupon> grouponList = promotionService.queryGroupons();
                int maxGrouponId = 1;
                for (Groupon iterator : grouponList) {
                    maxGrouponId = maxGrouponId > iterator.getGrouponId() ? maxGrouponId : iterator.getGrouponId();
                }
                groupon.setGrouponId(maxGrouponId + 1);
                // 自增
                groupon.setId(null);
                groupon.setOrderId(order.getId());
                // 这里不让下单，只让拼好团下单
                groupon.setPayed(false);
                groupon.setRulesId(grouponRulesId);
                // 分享的url
                groupon.setShareUrl("http://127.0.0.1:8083/wx/storage/fetch/176807a2-e573-499a-8120-b922bbe6a5a0.jpeg");
                groupon.setUpdateTime(date);
                groupon.setUserId(user.getId());

                promotionService.addGroupon(groupon);
                HashMap<String, Integer> map = new HashMap<>();
                map.put("orderId", order.getId());
                return BaseRespVo.fail3(map);
            }


            // 状态初始为已付款 201
            order.setOrderStatus((short) 201);
            // 支付id todo 不知道怎么传 先给个orderSn
            order.setPayId(order.getOrderSn());
            order.setPayTime(date);
            // 默认都是顺丰发货
            order.setShipChannel("顺丰");
            // 编号 todo 不知道怎么传 先给个orderSn
            order.setShipSn(order.getOrderSn());
            // 假设 7天后发货
            order.setShipTime(new Date(date.getTime() + 7 * 24 * 60 * 60 * 1000));

            orderService.addOrder(order);

            // 使用优惠券，couponUser要减少
            CouponUser couponUser = new CouponUser();
            couponUser.setStatus((short) 1);
            couponUser.setUsedTime(date);
            couponUser.setUpdateTime(date);
            couponUser.setOrderId(order.getId());
            promotionService.changeCouponUserByCouponIdAndUserId(couponUser, couponId, user.getId());


            for (Cart cart : cartList) {

                // orderGoods增加
                Integer goodsId = cart.getGoodsId();
                GoodsDetailVo goodsDetailVo = goodsService.queryGoodsDetail(goodsId);
                OrderGoods orderGoods = new OrderGoods();

                orderGoods.setAddTime(date);
                orderGoods.setComment(null);
                orderGoods.setDeleted(false);
                orderGoods.setGoodsId(cart.getGoodsId());
                orderGoods.setGoodsName(cart.getGoodsName());
                orderGoods.setGoodsSn(cart.getGoodsSn());
                // 自增
                orderGoods.setId(null);
                orderGoods.setNumber(cart.getNumber());
                orderGoods.setOrderId(order.getId());
                orderGoods.setPicUrl(goodsDetailVo.getGoods().getPicUrl());
                // todo 不知道什么价格 写了一个零售价格
                orderGoods.setPrice(goodsDetailVo.getGoods().getRetailPrice());
                orderGoods.setProductId(cart.getProductId());
                orderGoods.setSpecifications(cart.getSpecifications());
                orderGoods.setUpdateTime(date);
                orderService.addOrderGoods(orderGoods);

                // goodsproduct减少数量
                GoodsProduct goodsProduct = goodsService.queryGoodsProductById(cart.getProductId());
                GoodsProduct goodsProduct1 = new GoodsProduct();
                goodsProduct1.setNumber(goodsProduct.getNumber() - cart.getNumber());
                goodsService.changeGoodsProductById(goodsProduct, cart.getProductId());
            }

            // 再把cartList清空
            ArrayList<Integer> idList = new ArrayList<>();
            for (Cart cart : cartList) {
                idList.add(cart.getId());
            }
            cartService.removeCartByIdList(idList);

            HashMap<String, Integer> map = new HashMap<>();
            map.put("orderId", order.getId());
            return BaseRespVo.ok(map);
        }
    }


    @RequestMapping("goods")
    public BaseRespVo orderGoods(Integer orderId, Integer goodsId) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        OrderGoodsVo orderGoodsVo = orderService.queryGoodsOrder(orderId, goodsId, user);

        return BaseRespVo.ok(orderGoodsVo);
    }


}
